// 封装电话相关API
export const phoneApi = {
  // 根据userId获取用户电话列表
  getPhoneList: async (userId) => {
    const url = `http://localhost:6008/phone-client/api/phone/getPhoneListByUserId/${userId}`;

    const res = await uni.request({
      url: url,
      method: 'POST',
      timeout: 10000
    });

    // 统一响应处理
    if (res.statusCode !== 200) {
      throw new Error(`请求失败: ${res.statusCode}`);
    }
    if (res.errMsg.includes('fail')) {
      throw new Error(`网络错误: ${res.errMsg}`);
    }
    return res.data;
  },
  
  // 新增电话（修复版）
  addPhone: async (phoneData) => {
    // 验证必填字段
    if (!phoneData.userId || !phoneData.phoneNumber) {
      throw new Error('用户ID和电话号码为必填项');
    }
    
    const res = await uni.request({
      url: 'http://localhost:6008/phone-client/api/phone/insert',
      method: 'POST',
      data: {
        userId: phoneData.userId,
        phoneNumber: phoneData.phoneNumber,
        phoneAddress: phoneData.phoneAddress || '',
        status: phoneData.status || 1, // 默认启用
        supplier: phoneData.supplier || ''
      },
      timeout: 10000
    });

    if (res.statusCode !== 200) {
      throw new Error(`请求失败: ${res.statusCode}`);
    }
    if (res.errMsg.includes('fail')) {
      throw new Error(`网络错误: ${res.errMsg}`);
    }
    return res.data;
  },
  
  // 删除电话（修复版）
  deletePhone: async (phoneId) => {
    if (!phoneId) {
      throw new Error('电话ID为必填项');
    }
    
    const res = await uni.request({
      url: `http://localhost:6008/phone-client/api/phone/delete/${phoneId}`,
      method: 'POST',
      timeout: 10000
    });

    if (res.statusCode !== 200) {
      throw new Error(`请求失败: ${res.statusCode}`);
    }
    if (res.errMsg.includes('fail')) {
      throw new Error(`网络错误: ${res.errMsg}`);
    }
    return res.data;
  },
  
  // 更新电话状态
  updatePhoneStatus: async (phoneId, status) => {
    if (!phoneId || status === undefined) {
      throw new Error('电话ID和状态为必填项');
    }
    
    const res = await uni.request({
      url: 'http://localhost:6008/phone-client/api/phone/updateStatus',
      method: 'POST',
      data: {
        phoneId: phoneId,
        status: status // 0停用，1启用
      },
      timeout: 10000
    });

    if (res.statusCode !== 200) {
      throw new Error(`请求失败: ${res.statusCode}`);
    }
    if (res.errMsg.includes('fail')) {
      throw new Error(`网络错误: ${res.errMsg}`);
    }
    return res.data;
  }
};